﻿@model Apps.Models.WMS.WMS_ReturnOrderModel
@using Apps.Web.Core;
@using Apps.Common;
@using Apps.Models.WMS;
@using Apps.Web;
@using Apps.Locale;
@using Apps.Models.Sys;
@{
    ViewBag.Title = "创建退货单";
    Layout = "~/Views/Shared/_Index_LayoutEdit.cshtml";
    List<permModel> perm = null;
}
<script type="text/javascript">
    //所选择行的退货数求和
    var sum_CurReturnQty = 0;
    var sum_CurLossQty = 0;
    //编辑的行
    var editIndex = undefined;
    //是否全部退货
    var isSelectAll = false;

    $(function ()
    {
        //加载到货单
        $("#btnLoadSupplier").click(function ()
        {
            isSelectAll = false;
            var supplierId = $("#SupplierId").val();
            var supplierShortName = $("#Supplier").val();
            sum_CurReturnQty = 0;
            sum_CurLossQty = 0;
            editIndex = undefined;
            $("#List").datagrid("load", { supplierId: supplierId, supplierShortName: supplierShortName });
            $("#List").datagrid("uncheckAll");
            setFooter();
        });

        //全退：全选、并且“本次退货数量”=“应退货数量”
        $("#btnLoadSupplierAndSelectAll").click(function ()
        {
            isSelectAll = true;
            var supplierId = $("#SupplierId").val();
            var supplierShortName = $("#Supplier").val();
            sum_CurReturnQty = 0;
            sum_CurLossQty = 0;
            editIndex = undefined;
            $("#List").datagrid("load", { supplierId: supplierId, supplierShortName: supplierShortName });
            //$("#List").datagrid("checkAll");
            setFooter();
        });

        $("#btnSave").click(function ()
        {
            if (!$("form").valid()) {
                $.messageBox5s('提示', $("#ErrMesList").html());
                return;
            }
            if ($("form").valid())
            {
                endEditing();
                var $dg = $('#List');
                var rows = $dg.datagrid('getChecked');  //获取被选中的行。
                //将所选中的行转换成json字符串，并保存到inserted隐藏输入框中。
                $("#inserted").val(JSON.stringify(rows));
                if (rows.length)
                {
                    showLoading();
                    $.ajax({
                        url: "@Url.Action("Print")",
                        type: "Post",
                        data: $("form").serialize(),
                        dataType: "json",
                        success: function (data)
                        {
                            if (data.type == 1)
                            {
                                hideLoading();
                                //送检退货打开报表打印的窗口
                                self.location = '@Url.Action("ShowBill", "ReportManager", new { area = "Report" })?reportCode=ReturnOrder&billNum=' + data.value;
                            } else
                            {
                                if (data.type == 2) {
                                hideLoading();
                                //库存退货打开报表打印的窗口
                                    self.location = '@Url.Action("ShowBill", "ReportManager", new { area = "Report" })?reportCode=InvReturnOrder&billNum=' + data.value;
                                }
                                else {
                                    window.parent.frameReturnByMes(data.message);
                                    hideLoading();}                                

                            }
                        }
                    })
                }
            }
        });
        $("#btnReturn").click(function () {
            window.parent.frameReturnByClose();
        });

        $(window).resize(function () {
            $('#List').datagrid('resize', {

            }).datagrid('resize', {
                width: SetGridWidthSub(30),
                height: SetGridHeightSub(50)
            });
        });

    });
    $(function ()
    {
        $('#List').datagrid({
            url: '@Url.Action("GetReturnOrderListBySupplier")?supplierId=&supplierShortName=',
            width: SetGridWidthSub(10),
            methord: 'post',
            height: SetGridHeightSub(100),
            fitColumns: true,
            idField: 'Id',
            pageSize: 15,
            pageList: [15, 20, 30, 40, 50],
            pagination: false,
            striped: true, //奇偶行是否区分
            singleSelect: true,//单选模式
            selectOnCheck: false,
            checkOnSelect: false,
            onClickCell: onClickCell,
            onEndEdit: onEndEdit,
            onBeginEdit: onBeginEdit,

            //onCheck: onCheck,
            //onUncheck: onUncheck,
            //onCheckAll: onCheckAll,
            //onUncheckAll: onUncheckAll,

            remotesort: false,
            showFooter: true,

            onLoadSuccess: function (data)
            {
                if (data.rows.length > 0)
                {
                    $("input[type='checkbox']")[0].disabled = true;
                    //循环判断操作为新增的不能选择
                    for (var i = 0; i < data.rows.length; i++)
                    {
                        $("input[type='checkbox']")[i + 1].disabled = true;

                        if (isSelectAll)
                        {
                            $("input[type='checkbox']")[i + 1].checked = true;
                            data.rows[i].CurReturnQty = data.rows[i].ReturnQty - data.rows[i].AdjustQty;
                            var td1 = $('.datagrid-body td[field="CurReturnQty"]')[i];
                            var div1 = $(td1).find('div')[0];
                            $(div1).text(data.rows[i].CurReturnQty);

                            data.rows[i].CurLossQty = 0;
                            var td2 = $('.datagrid-body td[field="CurLossQty"]')[i];
                            var div2 = $(td2).find('div')[0];
                            $(div2).text(data.rows[i].CurLossQty);
                        }
                    }

                    if (isSelectAll)
                    {
                        $("#List").datagrid("checkAll");
                        onEndEdit(0, null);
                    }
                }
                else
                {
                    if ($("#Supplier").val() != '')
                        alert('没有需要处理的数据！');
                }
            },

            //onCheckAll: function (rows)
            //{
            //    if (rows.length > 0)
            //    {
            //        for (var i = 0; i < rows.length; i++)
            //        {
            //            rows[i].Qty = rows[i].ReturnQty;
            //        }
            //    }
            //},

            columns: [[
                {
                    field: 'ck', checkbox: true,
                },
                { field: 'SupplierShortName', title: '供应商简称', width: 80, sortable: true },
                { field: 'InspectBillNum', title: '检验单号', width: 80, sortable: true },
                { field: 'PartCode', title: '物料编码', width: 80, sortable: true },
                { field: 'ArrivalQty', title: '到货数量', width: 80, sortable: true, align: 'right' },
                { field: 'QualifyNum', title: '合格数量', width: 80, sortable: true, align: 'right' },
                { field: 'NoQualifyNum', title: '不合格数量', width: 80, sortable: true, align: 'right' },
                { field: 'ReturnQty', title: '应退货数量', width: 80, sortable: true, align: 'right' },
                { field: 'AdjustQty', title: '已退货数量', width: 80, sortable: true, align: 'right' },
                { field: 'LossQty', title: '已报废数量', width: 80, sortable: true, align: 'right' },
                {
                    field: 'CurReturnQty', title: '本次退货数量', width: 80, sortable: true, align: 'right',
                    editor: { type: 'numberbox' }
                },
                {
                    field: 'CurLossQty', title: '本次报废数量', width: 80, sortable: true, align: 'right',
                    editor: { type: 'numberbox' }
                },
                { field: 'InvName', title: '库房', width: 80, sortable: true },
                { field: 'Lot', title: '批次', width: 80, sortable: true },
                { field: 'Remark', title: '说明', width: 80, sortable: true, editor: { type: 'textbox' } },
            ]]
        });
    })

    //function onCheck(index, row)
    //{
    //    endEditing();
    //    sum_Qty = sum_Qty + Number(row.Qty);
    //    setFooter();
    //}
    //function onUncheck(index, row)
    //{
    //    //endEditing();
    //    sum_Qty = sum_Qty - Number(row.Qty);
    //    setFooter();
    //}
    //function onCheckAll(rows)
    //{
    //    endEditing();
    //    sum_Qty = 0;
    //    for (var i = 0; i < rows.length; i++)
    //    {
    //        sum_Qty = sum_Qty + Number(rows[i]['Qty']);
    //    }
    //    setFooter();
    //}
    //function onUncheckAll(rows)
    //{
    //    //endEditing();
    //    sum_Qty = 0;
    //    setFooter();
    //}

    function setFooter()
    {
        $('#List').datagrid('reloadFooter',
            [
                { SupplierShortName: '合计：', CurReturnQty: sum_CurReturnQty, CurLossQty: sum_CurLossQty },
            ]
        );
    }

    function setKeyUpValue(sender)
    {
        var row = $('#List').datagrid('getSelected');
        var rowIndex = $('#List').datagrid('getRowIndex', row);//获取行号
        var thisTarget_CurReturnQty = $('#List').datagrid('getEditor', { 'index': rowIndex, 'field': 'CurReturnQty' }).target;
        var thisTarget_CurReturnQty_Input = $(thisTarget_CurReturnQty).data('numberbox') ? $(thisTarget_CurReturnQty).numberbox('textbox') : $(thisTarget_CurReturnQty);
        var thisTarget_CurLossQty = $('#List').datagrid('getEditor', { 'index': rowIndex, 'field': 'CurLossQty' }).target;
        var thisTarget_CurLossQty_Input = $(thisTarget_CurLossQty).data('numberbox') ? $(thisTarget_CurLossQty).numberbox('textbox') : $(thisTarget_CurLossQty);

        if ((thisTarget_CurReturnQty_Input.val() != 0) || (thisTarget_CurLossQty_Input.val() != 0))
        {
            $('#List').datagrid('checkRow', rowIndex);
        }
        else
        {
            $('#List').datagrid('uncheckRow', rowIndex);
        }

        $("input[type='checkbox']")[rowIndex + 1].disabled = true;
    }


    function endEditing()
    {
        if (editIndex == undefined) { return true }
        $('#List').datagrid('endEdit', editIndex);

        //执行上面的代码会使得checkbox可编辑，需要手工再次设置disabled = true
        $("input[type='checkbox']")[editIndex + 1].disabled = true;

        editIndex = undefined;
        return true;
    }
    function onClickCell(index, field)
    {
        if (editIndex != index)
        {
            if (endEditing())
            {
                $('#List').datagrid('selectRow', index)
                    .datagrid('beginEdit', index);

                //给numberbox增加keyup事件，以便自动计算合格数量和不合格数量
                var eds = $('#List').datagrid('getEditors', index);
                for (var i = 0; i < eds.length; i++)
                {
                    var ed = eds[i];
                    //alert(ed.field);
                    if ((ed.field == 'CurReturnQty') || (ed.field == 'CurLossQty'))
                    {
                        var target = $(ed.target).data('numberbox') ? $(ed.target).numberbox('textbox') : $(ed.target);
                        target.attr("field", ed.field)
                        target.bind("keyup", function ()
                        {
                            return setKeyUpValue($(this));
                        });
                    }

                    if (ed.field == 'CurReturnQty')
                    {
                        var target = $(ed.target).data('numberbox') ? $(ed.target).numberbox('textbox') : $(ed.target);
                        ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                    }
                }

                editIndex = index;
            } else
            {
                setTimeout(function ()
                {
                    $('#List').datagrid('selectRow', editIndex);
                }, 0);
            }
        }
    }
    function onEndEdit(index, row)
    {
        var rows = $('#List').datagrid("getChecked");
        sum_CurReturnQty = 0;
        sum_CurLossQty = 0;
        for (var i = 0; i < rows.length; i++)
        {
            sum_CurReturnQty = sum_CurReturnQty + Number(rows[i]['CurReturnQty']);
            sum_CurLossQty = sum_CurLossQty + Number(rows[i]['CurLossQty']);
        }
        setFooter();
   }

    //进入编辑前设置
    function onBeginEdit(index, row)
    {
    }

    function removeit()
    {
        if (editIndex == undefined) { return }
        $('#List').datagrid('selectRow', editIndex);

        $('#List').datagrid('cancelEdit', editIndex)
            .datagrid('deleteRow', editIndex);
        editIndex = undefined;
    }

    function reject()
    {
        $('#List').datagrid('rejectChanges');
        editIndex = undefined;
    }
    function getChanges()
    {
        var rows = $('#List').datagrid('getChanges');
        alert(rows.length + ' rows are changed!');
    }

    function contains(arr, obj)
    {
        var i = arr.length;
        while (i--)
        {
            if (arr[i] === obj)
            {
                return true;
            }
        }
        return false;
    }


    //关闭模式窗口
    function frameReturnByClose() {
        $("#modalwindow").window('close');
    }

    //ifram 返回
    function frameReturnByClose() {
        $("#modalwindow").window('close');
    }

    function frameReturnByMes(mes) {
        $.messageBox5s('提示', mes);
    }
</script>

<div id="modalwindow" class="easyui-window" style="width:800px; height:400px;" data-options="modal:true,closed:true,minimizable:false,shadow:false"></div>
<div class="mvctool bgb">
    @Html.ToolButton("btnSave", "fa fa-save", Resource.Print, ref perm, "Save", true)
    @Html.ToolButton("btnReturn", "fa fa-reply", Resource.Reply, false)
</div>
@using (Html.BeginForm())
{
    <div id="ErrMesList">
        <div id="ErrMesListContent">
            @Html.ValidationSummary(false)
        </div>
    </div>
    @*@Html.HiddenFor(model => model.Id)*@
    <input id="inserted" type="hidden" name="inserted" value="" />
    <table class="formtable">
        <tbody>
            <tr>
                <th>
                    @Html.LabelFor(model => model.SupplierShortName)：
                </th>
                <td>
                    <div style="height:0;width:0;overflow:hidden">
                        @Html.TextBoxFor(model => model.SupplierId)
                    </div>
                    <input id="Supplier" name="Supplier" type="text" style="width: 200px; display: inline;">
                    <a class="fa fa-plus-square color-gray fa-lg" id="selExc" href="javascript:showSelSupplier()"></a>
                    <script type="text/javascript">
                        function showSelSupplier()
                        {
                            $("#modalwindow").html("<iframe width='100%' height='100%' scrolling='no' frameborder='0'' src='/WMS/ReturnOrderD/SupplierLookUp'></iframe>");
                            $("#modalwindow").window({ title: '选择供应商', width: 720, height: 488, iconCls: 'fa fa-plus' }).window('open');
                        }

                        function SetSelResult(result, resultName)
                        {
                            $("#SupplierId").val(result);
                            $("#Supplier").val(resultName);
                        }

                    </script>
                    @Html.ToolButton("btnLoadSupplier", "fa fa-reply", Resource.Load, false)
                    @Html.ToolButton("btnLoadSupplierAndSelectAll", "fa fa-list", "加载且全退", false)
                </td>
                @*<th>
                        @Html.LabelFor(model => model.InStoreBillNum) （自动生成）：
                    </th>
                    <td>
                        <input id="inStoreBillNum" type="hidden" name="inStoreBillNum" value="@ViewBag.ArrivalBillNum" />
                        @Html.TextBox("inStoreBillNum", (string)ViewBag.InStoreBillNum, new { @disabled = "disabled" })
                    </td>*@
                @*<th>
                        @Html.LabelFor(model => model.InvCode):
                    </th>
                    <td>
                        @Html.DropDownListFor(model => model.InvCode, ViewBag.Inv as SelectList)
                    </td>*@
            </tr>

        </tbody>
    </table>
}
<table>
    <tr>
        <td colspan="7" style="padding:4px;">
            <table id="List"></table>
        </td>
    </tr>

</table>
